<template>
  <div class="accountPage">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-bank-card">  mac管理</i> 
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="addAccountBox" v-if="hasPerm('user:add')">
      <el-button type="primary" size="mini" @click="addMac" >添加账号</el-button>
    </div>
    <el-table class="accountTable" :data="list" height="470px" border>
      <el-table-column
        label="序号"
        width="60"
        align="center"
      >
       <template slot-scope="scope">
            {{scope.$index + 1}}
        </template></el-table-column>
      <el-table-column prop="mac" label="mac"  align="center"></el-table-column>
      <el-table-column label="创建日期"  align="center">
        <template slot-scope="scope">
          {{scope.row.createTime | timeFormat}}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.available">
            正常
          </el-tag>
          <el-tag v-else type="danger">
            禁用
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260"  align="center"  v-if="hasPerm('user:upa') ||hasPerm('user:delete') ">
        <template slot-scope="scope">
          <el-button
           v-if="hasPerm('user:upa')"
            type="text"
            icon="el-icon-edit"
            class="btn-sz"
            @click="updateAccount(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
          v-if="scope.row.available && hasPerm('user:delete')"
            type="text"
            icon="el-icon-delete"
            class="red btn-sz"
            @click="changeStatu(scope.row,'禁用')"
            >禁用</el-button
          >
          <el-button
          v-if="!scope.row.available && hasPerm('user:delete')"
            type="text"
            icon="el-icon-delete"
            class="red btn-sz"
            @click="changeStatu(scope.row,'启用')"
            >启用</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="queryInfo.pagenum"
          :page-size="queryInfo.pagesize"
          :total="pageTotal"
          @current-change="handlePageChange"
      ></el-pagination>
    </div>

    <!-- 对话框区域 -->
     <el-dialog v-dialogDrag width="500px" @close="blankAccount" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="tempMac" status-icon  :rules="accountRule" ref="accountForm"   label-position="left" label-width="100px"  style='width: 460px; margin-left:20px; height:400px;'>
        <el-form-item prop="mac" label="mac信息" required >
          <el-input   v-model="tempMac.mac" style="width: 250px;">
          </el-input>
        </el-form-item>
        <el-form-item label="分组名" required="">
        <template>
          <el-select v-model="tempMac.macGroupId" placeholder="请选择分组名">
            <el-option
              v-for="item in optionsGroupArr"
              :key="item.id"
              :label="item.macGroupName"
              :value="item.id">
            </el-option>
          </el-select>
        </template>
        </el-form-item>
        <el-form-item  label="状态" required>
          <el-switch
          v-model="macSwitch"
          active-text="启用"
          inactive-text="禁用"
          >
         </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="blankAccount">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="success" @click="createMac">创 建</el-button>
        <el-button type="primary" v-else @click="editAccount">修 改</el-button> 
      </div>
     </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { commonGetMacinfoList,commonGetMacinfoAdd,commonGetMacinfoUpa,commonGetMacinfoByid } from '../../../service/common.js'
export default {
  data() {
    return {
      roleListIdArrTwo:'',
      // 重置密码弹窗数据
      newPassword:{
        id:'',
        password:''
      },
      dialogPassword:false, //重置密码弹窗
      optionsValue:'2', //下拉框的值
      // 查询数据
      options: [
        {
          value: "0",
          label: "禁用",
        },
        {
          value: "1",
          label: "正常",
        },
        {
          value: "2",
          label: "所有",
        },
      ],
      //规则
      accountRule: {
        mac:[
           { validator: this.validateMac, trigger: 'blur' }
        ]
      },
      queryInfo: {
        pagenum: 1,
        pagesize: 2,
      },
      dialogFormVisible:false, //对话框开关
       //对话框状态映射
      textMap: {
        update: '编辑mac信息',
        create: '新建mac信息'
      },
      dialogStatus:'create', //对话框状态
      tempMac:{
        mac:'', //账号
        available:'', //状态
        id:'',
        macGroupId:''
      },
      macSwitch:false, //状态
      roleList:[], //角色数组
      roleListIdArr:[], //角色id数组
      pageTotal: 0, //总页数
      // 查询数据
      formInline: {
        mac: "",
        macGroupName:'',
        available:''
      },
      // 表格数据
      list: [],
      optionsGroupArr:[],
      MacGroupList:[]
    };
  },
  created() {
    this.getMacList()
  },
  methods: {
    validateMac(rule, value, callback) {
      if (!value) {
        return callback(new Error('请输入mac'));
      }else {
        if (this.checkMac(value)) {
          callback()
        }else {
          return callback(new Error('mac校验失败'));
        }
      }
    },
        // 检查mac
    checkMac(value) {
      let pattern = /([\u2E80-\u9FFF]|\w|[,，\.。])*/;
      let regNum = /^[0-9a-z]*$/
      if(!pattern.test(value) || !regNum.test(value)) {
        return false
      }else {
        return  true
      }
    },
    // 获取mac列表
    async getMacList() {
    try {
      console.log(this.queryInfo,'this.queryInfo')
      const res = await commonGetMacinfoList(this.queryInfo)
      console.log('res:获取mac列表 ', res);
      if (res.code == '200') {
        this.list = res.sysUsers.records
        this.pageTotal = res.sysUsers.total
        this.MacGroupList = res.operationMacGroupList
        let arr =[]
        res.operationMacGroupList.forEach(item => {
          let obj = {}
          obj.macGroupName = item.macGroupName
          obj.id = item.id
          arr.push(obj)
        })
        this.optionsGroupArr = arr
        console.log( this.optionsGroupArr,' this.optionsGroupArr')
      }
      } catch (error) {
        this.$message.success(error)
      }
    },
    // 添加mac接口
    createMac() {
    this.$refs.accountForm.validate( async (valid) => {
     if (valid) {
      if (this.macSwitch) {
        this.tempMac.available = 1
      }else {
        this.tempMac.available = 0
      }
      try {
      const res = await commonGetMacinfoAdd(this.tempMac)
      console.log('res:新增 ', res);
      if(res.code == "200") {
        this.$message.success(res.msg);
        this.blankAccount()
        this.getMacList()
      }else {
        this.$message.success(res.msg);
      }
      } catch (error) {
        this.$message.error('添加账号接口异常');
        this.$message.error(error);
      }
        }else {
          this.$message.error('error submit!!')
          return false
        }
      })

    },
    // 添加mac按钮
    addMac() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 编译mac
    async editAccount() {
    this.$refs.accountForm.validate( async (valid) => { 
      if (valid) {
       if (this.macSwitch) {
        this.tempMac.available = 1
      }else {
        this.tempMac.available = 0
      }
      try {
      const res = await commonGetMacinfoUpa(this.tempMac)
      console.log('res: 修改', res);
      if(res.code == "200") {
        this.$message.success(res.msg);
        this.getMacList()
        this.blankAccount()
      }else {
        this.$message.success(res.msg);
      }
      } catch (error) {
        this.$message.error('编译账号接口异常');
        this.$message.error(error);
      }
      }else {
          this.$message.error('error submit!!')
          return false
        }
    }
    )
    },
    // 编译按钮
    async updateAccount(index,row) {
      console.log(row,index)
      try {
        this.tempMac.macGroupId = Number(row.macGroupId)
        this.tempMac.id = row.id
        this.tempMac.mac = row.mac
        this.tempMac.available = row.available
        if (row.available == 1) {
          this.macSwitch = true
        }else {
          this.macSwitch = false
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      } catch (error) {
        this.$message.error('异常操作')
        console.log(error,'异常操作error')
      }

    },
    // 点击取消弹窗 
    blankAccount() {
      this.tempMac.mac = ''
      this.tempMac.id = ''
      this.tempMac.macGroupId = ''
      this.dialogStatus = 'create'
      this.macSwitch = false
      this.dialogFormVisible = false
    },
    // 查询
    async onFindAccount() {
      if (this.optionsValue == '2') {
       this.formInline.available = ''
      }else if (this.optionsValue == '1') {
        this.$set(this.formInline,'available',1)
      }else {
        this.$set(this.formInline,'available',0)
      }
      try {
      const res = await commonGetMacinfoList(this.formInline)
      if (res.code == '200') {
       this.list = res.sysUsers.records
       this.pageTotal = res.sysUsers.length
      }
      } catch (error) {
         this.$message.success(error)
      }
    },
    // 重置
    onBlank() {
      this.getMacList()
      this.getRoleList()
    },
        // 删除操作
    changeStatu(row,state) {
      console.log(row,state,'删除')
      let available 
      if (row.available) {
        available = 0
      }else {
        available = 1
      }
      console.log('传入的状态',available)
        // 二次确认删除
        this.$confirm(`确定要${state}吗？`, '提示', {
            type: 'warning'
        })
        .then(async () => {
           let param = {
            id:row.id,
            macGroupId:row.macGroupId,
            available: available
           }
           console.log('param禁用参数',param)
           const res =  await commonGetMacinfoUpa(param)
           console.log('res:状态 ', res);
            // this.$message.success(`${state}成功`);
            this.getMacList()
        })
        .catch(() => {});
    },
      // 分页导航
    handlePageChange(val) {
      this.$set(this.queryInfo, 'pagenum', val);
      this.getMacList()
    },
  },
  computed: {
     ...mapGetters(["userId"]),
  }
};
</script>

<style lang="less" scoped>
.accountPage {
  min-width: 100%;
  height: 100%;
  border-radius: 5px;
  padding-top: 15px;
  padding-left: 20px;
  background-color: #fff;

  .accountTable {
    margin-top: 10px;
    width: 100%;
    overflow: auto;
  }

  .handle-box {
    margin-top: 10px;
    margin-bottom: 0px!important;
  }

  // .addAccountBox {
  //   height: 80px;
  //   padding: 20px 0 20px 0;
  // }

  .table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
  }

 .pagination {
   margin: 20px 0;
   text-align: right;
 }

}
</style>